package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.HmdpException;
import com.hmdp.utils.RedisConstant;
import com.hmdp.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public List<ShopType> getCategory() throws JsonProcessingException {
        String shop_type_string = stringRedisTemplate.opsForValue().get(RedisConstant.Shop_type);

        if (StringUtils.isNotBlank(shop_type_string)) {
            List<ShopType> shopTypes = objectMapper.readValue(shop_type_string, new TypeReference<List<ShopType>>() {
            });
            return shopTypes;
        }

        List<ShopType> ShopTypeList = this.list();
        if (ShopTypeList == null) {
            throw new HmdpException(ResultCodeEnum.DATA_ERROR);
        }

        String json = objectMapper.writeValueAsString(ShopTypeList);
        stringRedisTemplate.opsForValue().set(RedisConstant.Shop_type, json);

        return ShopTypeList;
    }
}
